<?php

namespace Web\MainSiteBundle\Controller;

use Model\CourseBundle\Entity\Course;
use Model\CourseBundle\Entity\CourseExam;
use Model\CourseBundle\Entity\CourseLessonArrange;
use Model\CourseBundle\Model\CourseLessonArrangeModel;
use Model\CourseBundle\Model\CourseLessonContentModel;
use Model\CourseBundle\Model\CourseModel;
use Model\CourseCategoryBundle\Model\CourseCategoryModel;
use Model\ExamBundle\Model\ExamModel;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;

/**
 * @route("/course")
 */
class ManageCourseController extends WebBaseController
{
    /**
     * @route("/info/add",name="WebCourseInfoAdd")
     */
    public function WebCourseInfoAdd(Request $request)
    {
        $user = $this->needToBeTeacher();
        $courseModel = new CourseModel($this->getDoctrine());
        if ($request->getMethod() == "POST") {
            //新增课程动作
            if (!$title = $this->getParamRequired("title")) {$this->showMessagePage("课程标题不能为空");}
            if (!$category = $this->getParamRequired("category")) {$this->showMessagePage("请选择课程分类");}
            if (!$info = $this->getParamRequired("info")) {$this->showMessagePage("请填写课程简介");}
            $data = array(
                "title"     => $title,
                "userId"    => $user->getId(),
                "category"  => $category,
                "info"      => $info,
                "uniqueId"  => md5(time().$user->getId().uniqid())
            );
            $re = $courseModel->commAdd($data);
            if ($re) {
                //跳转到课程首页
                return $this->redirectToRoute("WebCourseInfoManage",array("uniqueId"=>$re));
            } else {
                $this->showMessagePage("系统错误");
                return "程序永远不会走到这里";
            }
        } else {
            //表单页
//            $courseCategory = new CourseCategoryModel($this->getDoctrine());//获取所有课程分类
//            $courseCategory = $courseCategory->getAllCourseCategory();
//            $data = array();
            $CourseCategory = new CourseCategoryModel($this->getDoctrine());
            $groups = $CourseCategory->getAllGroupByParent();

            $data = array(
                "sorts" => json_encode($groups),
//                "courseCategory" => $courseCategory,
            );
            return $this->render("WebMainSiteBundle:Course:course_add.html.twig",$data);
        }
    }

    /**
     * @route("/info/manage/{uniqueId}",name="WebCourseInfoManage")
     */
    public function WebCourseInfoManage(Request $request , Course $course)
    {
        $this->needToBeCourseManager($course);
        $courseModel = new CourseModel($this->getDoctrine());
        if ($request->getMethod() == "POST") {
            //管理课程动作
            if (!$title = $this->getParamRequired("title")) {$this->showMessagePage("课程标题不能为空");}
            if (!$category = $this->getParamRequired("category")) {$this->showMessagePage("请选择课程分类");}
            if (!$info = $this->getParamRequired("info")) {$this->showMessagePage("请填写课程简介");}
            $data = array(
                "id"        => $course->getId(),
                "title"     => $title,
                "category"  => $category,
                "info"      => $info,
                "uniqueId"  => $course->getUniqueId(),
            );
            $re = $courseModel->commUpdate($data);
            if ($re) {
                //跳转到课程首页
                return $this->redirectToRoute("WebCourseInfoManage",array("uniqueId"=>$re));
            } else {
                $this->showMessagePage("系统错误");
                return "程序永远不会走到这里";
            }
        } else {
            //管理表单页
            $courseCategory = new CourseCategoryModel($this->getDoctrine());//获取所有课程分类
            $courseCategory = $courseCategory->getAllCourseCategory();
            $data = array("courseCategory" => $courseCategory);
            $data["course"] = $course;

            $CourseCategory = new CourseCategoryModel($this->getDoctrine());
            $groups = $CourseCategory->getAllGroupByParent();
//            $data = array(
//                "sorts" => json_encode($groups),
//            );
            $data["sorts"] = json_encode($groups);

            //如果传入id则尝试获取数据进行修改
            if ($id = $course->getCategory()) {

                $rep = $this->getDoctrine()->getRepository("ModelCourseCategoryBundle:CourseCategory");
                $Sort = $rep->find($id);
                $link = $Sort->getLink();
                $link = str_replace("]","",$link);
                $linkArr = explode("[",substr($link,1));


                $data["Sort"] = json_encode($linkArr);

            }



            return $this->render("WebMainSiteBundle:Course:course_edit.html.twig",$data);
        }
    }

    /**
     * @route("/list/my",name="WebTeacherCourseList")
     */
    public function WebTeacherCourseList()
    {//获取课程列表
        $user = $this->needToBeTeacher();
        $userId = $user->getId();
        $data  = array();
        //构建列表条件
        if (!$p = $this->getParamRequired("p")) {$p = 0;}
        $offset = $p*10;
        $params["conditions"]["Course"]["userId"]["eq"] = $userId;
        $params["orderBy"]["Course"]["id"] = "DESC";
        $courseModel = new CourseModel($this->getDoctrine());
        $listData = $courseModel->commLists($params,$offset);
        //取出数据
        $data["total"] = $listData["total"];
        $data["course"] = $listData["data"];
        return $this->render("WebMainSiteBundle:Course:course_list.html.twig",$data);
    }

    /**
     * @route("/picCover/{uniqueId}",name="WebCoursePicCover")
     */
    public function WebCoursePicCoverAction(Request $request , Course $course)
    {
        $this->needToBeCourseManager($course);
        $courseModel = New CourseModel($this->getDoctrine());
        if ($request->getMethod("POST") == "POST")
        {//更新账号信息
            if (!$picCover = $this->getParamRequired("pic")) {return $this->js_out("请选择新的图片");}
//            $data = array();
//            $data["picCover"] = $picCover;
//            $data["id"] = $course->getId();
//            $data["uniqueId"] = $course->getUniqueId();
//            $courseModel->commUpdate($data);
            $course->setPicCover($picCover);
            $em = $this->getDoctrine()->getManager();
            $em->persist($course);
            $em->flush();
        }
        $data = array("course" => $course);
        return $this->render("WebMainSiteBundle:Course:course_cover_pic.html.twig",$data);
    }

    /**
     * @route("/picMain/{uniqueId}",name="WebCoursePicMain")
     */
    public function WebCoursePicMainAction(Request $request , Course $course)
    {
        $this->needToBeCourseManager($course);
        $courseModel = New CourseModel($this->getDoctrine());
        if ($request->getMethod("POST") == "POST")
        {//更新账号信息
            if (!$picMain = $this->getParamRequired("pic")) {return $this->js_out("请选择新的图片");}
//            $data = array();
//            $data["picMain"] = $picCover;
//            $data["id"] = $course->getId();
//            $data["uniqueId"] = $course->getUniqueId();
//            $courseModel->commUpdate($data);

            $course->setPicMain($picMain);
            $em = $this->getDoctrine()->getManager();
            $em->persist($course);
            $em->flush();
        }
        $data = array("course" => $course);
        return $this->render("WebMainSiteBundle:Course:course_main_pic.html.twig",$data);
    }


    /**
     * @route("/Exams/{uniqueId}",name="WebCourseExams")
     */
    public function WebCourseExams(Request $request , Course $course)
    {

        $user = $this->needToBeTeacher();
        $courseId = $course->getId();


        if (!$type = $this->getParamRequired("type")) {
            $type = 0;
        } else {
            $type = 1;
        }

        $userId = $user->getId();
        $examModel = new ExamModel($this->getDoctrine());
        $examMixed = $examModel->get4Course($courseId,$userId);
        $newData = array();
        foreach ($examMixed as $key => $exam) {
            if (!isset($newData[$key])) {
                $newData[$key] = array();
            }
            foreach ($exam as $k => $v) {
                if ($v["type"] == $type) {
                    $newData[$key][] = $v;
                }
            }
        }
        $data = array(
            "exam" => $newData,
            "course" => $course,
            "type"   => $type,
        );
        return $this->render("WebMainSiteBundle:Course:course_add_exam.html.twig",$data);

    }

    /**
     * @route("/AddExam/{uniqueId}",name="WebCourseAddExam")
     */
    public function WebCourseAddExam(Request $request , Course $course)
    {

        $user = $this->needToBeTeacher();
        $courseId = $course->getId();
        if ($examId = $this->getParamRequired("examId")) {
            if (!$action = $this->getParamRequired("action")) {
                return $this->msg_out("系统错误");
            }

            $em = $this->getDoctrine()->getManager();
            if ($action == "add") {
                //加入
                $courseExam = new CourseExam();
                $courseExam->setExamId($examId);
                $courseExam->setCourseId($courseId);
                $em->persist($courseExam);
            } else {
                //移除
                $rep = $em->getRepository("ModelCourseBundle:CourseExam");
                $courseExam = $rep->findOneBy(array("courseId"   => $courseId,"examId"   => $examId));
                $em->remove($courseExam);
            }
            $em->flush();
        }

        if (!$type = $this->getParamRequired("type")) {
            $type = 0;
        } else {
            $type = 1;
        }
        return $this->redirectToRoute("WebCourseExams",array("uniqueId"=>$course->getUniqueId(),"type"   => $type));

    }
}
